package data

import (
	"commerce/common"
	"commerce/model"
	"database/sql"
	"fmt"
	"time"
)

func PageBanner(pageNo, pageSize int) (*common.Page, error) {

	row := common.DB.QueryRow("select count(*) FROM banner")
	var totalRecords int
	if err := row.Scan(&totalRecords); err != nil {
		return nil, err
	}
	stmt, err := common.DB.Prepare("select id, link, img_url, priority, is_valid, created_time FROM banner LIMIT ?, ?")
	if err != nil {
		return nil, err
	}
	defer stmt.Close()

	rows, err := stmt.Query((pageNo-1)*pageSize, pageSize)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var bs []model.Banner
	for rows.Next() {
		b := model.Banner{}
		if err := rows.Scan(&b.Id, &b.Link, &b.ImgUrl, &b.Priority, &b.IsValid, &b.CreatedTimeStr); err != nil {
			return nil, fmt.Errorf("banner 分页数据有误:%s", err.Error())
		}
		bs = append(bs, b)
	}
	return common.NewPage(bs, pageNo, pageSize, totalRecords), nil
}

func GetBannerById(id int) (*model.Banner, error) {

	sqlTpl := "select id, link, img_url, priority FROM banner where id = ?"

	stmt, err := common.DB.Prepare(sqlTpl)
	if err != nil {
		return nil, err
	}
	defer stmt.Close()

	var b model.Banner
	if err = stmt.QueryRow(id).Scan(&b.Id, &b.Link, &b.ImgUrl, &b.Priority); err != nil {
		return nil, err
	}
	return &b, nil
}

func AddBanner(b model.Banner) (int, error) {

	sqlTpl := "insert into banner(link, img_url, priority, created_time, updated_time) VALUES (?, ?, ?, ?, ?)"
	result, err := common.DB.Exec(sqlTpl, b.Link, b.ImgUrl, b.Priority, time.Now().Add(8*time.Hour), time.Now().Add(8*time.Hour))

	if err != nil {
		return 0, err
	}
	id, err := result.LastInsertId()

	if err != nil {
		return 0, fmt.Errorf("save banner insert id err: %v", err)
	}
	return int(id), nil
}

func UpdateBanner(b model.Banner) (int, error) {

	sqlTpl := "update banner set link = ?, img_url = ?, priority = ?, updated_time = ? WHERE id = ?"
	if len(b.ImgUrl) == 0 {
		sqlTpl = "update banner set link = ?, priority = ?, updated_time = ? WHERE id = ?"
	}
	stmt, err := common.DB.Prepare(sqlTpl)
	if err != nil {
		return 0, err
	}
	defer stmt.Close()

	var result sql.Result
	if len(b.ImgUrl) > 0 {
		result, err = stmt.Exec(b.Link, b.ImgUrl, b.Priority, time.Now().Add(8*time.Hour), b.Id)
	} else {
		result, err = stmt.Exec(b.Link, b.Priority, time.Now().Add(8*time.Hour), b.Id)
	}
	if err != nil {
		return 0, fmt.Errorf("update banner err:%v", err.Error())
	}
	rowsAffected, err := result.RowsAffected()
	return int(rowsAffected), err
}

func UpdateBannerStatus(status, id int) error {

	sqlTpl := "update banner set is_valid = ?, updated_time = ? WHERE id = ?"

	stmt, err := common.DB.Prepare(sqlTpl)
	if err != nil {
		return err
	}
	defer stmt.Close()

	_, err = stmt.Exec(status, time.Now().Add(8*time.Hour), id)
	if err != nil {
		return fmt.Errorf("update banner status:id:%d, err:%v", id, err.Error())
	}
	return err
}

// -------------app专用接口开始---------------------------

func ListBanner() ([]model.Banner, error) {

	stmt, err := common.DB.Prepare("select id, link, img_url FROM banner where is_valid = 1 order by priority desc")
	if err != nil {
		return nil, err
	}
	defer stmt.Close()

	rows, err := stmt.Query()
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var bs []model.Banner
	for rows.Next() {
		b := model.Banner{}
		if err := rows.Scan(&b.Id, &b.Link, &b.ImgUrl); err != nil {
			return nil, fmt.Errorf("banner app banner list 数据有误:%s", err.Error())
		}
		bs = append(bs, b)
	}
	return bs, nil
}
